#include <errno.h>
#include "lock.h"

#ifdef _WIN32
#include <string.h>
void lock_init(lock_t *lock)
{
    if(lock){
        pthread_mutex_init((struct pthread_mutex_t**)&(lock->lock), NULL);
    }
}

void lock(lock_t *lock)
{
    if(lock){
        pthread_mutex_lock((struct pthread_mutex_t*)lock->lock);
    }
}

void unlock(lock_t *lock)
{
    if(lock){
        pthread_mutex_unlock((struct pthread_mutex_t*)lock->lock);
    }
}

void lock_destroy(lock_t *lock)
{
    if(lock){
        pthread_mutex_destroy((struct pthread_mutex_t*)lock->lock);
    }
}
int applockfd;
int app_lock(char *file)
{
    return 1;   
}

void app_unlock()
{
}
#else
void lock_init(lock_t *lock)
{
	if (lock) {
		pthread_mutex_init(&lock->lock, NULL);
	}
}

void lock(lock_t *lock)
{
	if (lock) {
		pthread_mutex_lock(&lock->lock);
	}
}

void unlock(lock_t *lock)
{
	if (lock) {
		pthread_mutex_unlock(&lock->lock);
	}
}

void lock_destroy(lock_t *lock)
{
	if (lock) {
		pthread_mutex_destroy(&lock->lock);
	}
}

int applockfd;
int app_lock(char *file)
{
    applockfd=open(file, O_RDWR | O_CREAT, 0655);
    if (flock(applockfd, LOCK_NB | LOCK_EX) == -1) 
    {
        printf("[error]app is running.\r\n");
        exit(0);
    }
    return 1;   
}

void app_unlock()
{
    close(applockfd);
    flock(applockfd, LOCK_UN);
    return ;
}
#endif


